import axios from "axios";
import * as api from "../../api/gw";

/**
 * 
 * @param {*图片数组} params
 * @param {*成功的回调} callback 
 * @param {*失败的回调} errFn 
 */
export const uploadImg = function (params) {
    let axiosArr = [];
    params.forEach(item => {
        let formData = new FormData();
        formData.append("file", item);
        let options = {
            method: "post",
            url: window.api.mall_file_host + api.ImgUpload,
            timeout: 30000,
            data: formData
        }
        // console.log(window.api.mall_file_host + api.ImgUpload);
        axiosArr.push(axios(options));
    });
    return new Promise((resolve, reject) => {
        axios.all(axiosArr).then(axios.spread(function(...rest){
            console.log("rest", rest);
            //当这两个请求都完成的时候会触发这个函数，参数分别代表返回的结果
            //判断是否所有的请求都成功
            let state = true;
            let data = [];
            for (let item of rest) {
                if (item.status !== 200 || item.data.code !== 200) {
                    state = false;
                    break;
                } else {
                    data.push(item.data.visitPath);
                }
            }
            //都成功则执行成功的回调
            if (state) {
                //包装一下参数
                let obj = {
                    status: 1,
                    msg: "上传成功",
                    data
                }
                resolve(obj);
            } else {
                let obj = {
                    status: 0,
                    msg: "某个（些）图片上传失败",
                    data: []
                }
                reject(obj);
            }
        })).catch(err => {
            console.log(err);
            let obj = {
                status: 0,
                msg: "network error",
                err,
                data: []
            }
            reject(obj);
        });
    });
}